<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <TodoHeader :addTodo="addTodo"/>
      <TodoList :todos="todos" :deleteTodo="deleteTodo"></TodoList>
      <TodoFoot :todos="todos" :deleteCompleteTodos="deleteCompleteTodos" :selectAllTodos="selectAllTodos"/>
    </div>
  </div>
</template>

<script>
  import TodoHeader from "./components/TodoHeader";
  import TodoList from "./components/TodoList";
  import TodoFoot from "./components/TodoFoot";

  export default {
    name: "App",
    components: {TodoHeader, TodoList, TodoFoot},
    data() {
      return {
        // 从localStorage 读取todos
        todos: JSON.parse(window.localStorage.getItem('todos_key') || '[]') // 解析json字符串
        /*todos: [// 数据在哪定义，操作数据的行为就在那定义
          {title: 'xxx', complete: false},
          {title: 'yyy', complete: true},
        ]*/
      }
    },
    methods: {
      // 添加todo
      addTodo(todo) {
        this.todos.unshift(todo);
      },
      // 删除todo
      deleteTodo(index) {
        this.todos.splice(index, 1);
      },
      // 删除完成的todos
      deleteCompleteTodos() {
        this.todos = this.todos.filter(todo => !todo.complete);
      },
      // 全选 或者全部选 todo
      selectAllTodos(isCompleteAll) {
        this.todos = this.todos.map(todo => {
          return {
            title: todo.title,
            complete: isCompleteAll
          }
        })
      }
    },
    watch: {
      /*todos(newVal) { // 只能监视属性的变化
        // 存储到localStorage
      }*/
      todos: {// 深度监视,可以监视到属性内部的变化
        deep: true,
        handler: function (newValue, oldValue) {
          // 将todos最新的值保存到localStorage
          window.localStorage.setItem("todos_key", JSON.stringify(newValue));
        }

      }
    }
  }
</script>

<style scoped>
  /*app*/
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }

  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }

</style>
